package com.example.administrator.atfragment.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.style.ImageSpan;

/**
 * 垂直居中的ImageSpan
 * Created by baron
 * Date : 2016/5/10 0010 14:23
 * Email: 5267621@qq.com
 */
public class VerticalImageSpan extends ImageSpan {

    int fontHeight;

    public VerticalImageSpan(Context arg0, int arg1) {
        super(arg0, arg1);
    }

    public VerticalImageSpan(Context arg0, Drawable drawable) {
        super(drawable);
    }

    public VerticalImageSpan(Context arg0, Bitmap bitmap) {
        super(arg0, bitmap);
    }


    public int getSize(Paint paint, CharSequence text, int start, int end,
                       Paint.FontMetricsInt fm) {
        Drawable d = getDrawable();
        Rect rect = d.getBounds();
        if (fm != null) {
            Paint.FontMetricsInt fmPaint = paint.getFontMetricsInt();
            //获得文字、图片高度
            fontHeight = fmPaint.descent - fmPaint.ascent;
            int drHeight = rect.bottom - rect.top;
            //对于这段算法LZ表示也不解，正常逻辑应该同draw中的计算一样但是显示的结果不居中，经过几次调试之后才发现这么算才会居中
            int top = drHeight / 2 - fontHeight / 4;
            int bottom = drHeight / 2 + fontHeight / 4;

            fm.ascent = -bottom;
            fm.top = -bottom;
            fm.bottom = top;
            fm.descent = top;
        }
        return rect.right;
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end,
                     float x, int top, int y, int bottom, Paint paint) {
        Drawable b = getDrawable();
        canvas.save();
        int transY = 0;
        if (top == 0) {
            //第一行bottom值会发生变化
            transY = 4;
        } else {
            transY = top;
        }
        //XLog.e("11111111111", b.getBounds().toString() + "   " + top + "   " + bottom + "   " + x + "   " + y);
        //获得将要显示的文本高度-图片高度除2等居中位置+top(换行情况)
        //transY = (fontHeight - b.getBounds().bottom) / 2 + top;
        //XLog.e("11111 ", transY + "  ");
        //偏移画布后开始绘制
        canvas.translate(x, transY);
        b.draw(canvas);
        canvas.restore();
    }

}
